package org.example.filter;


import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.config.JwtProperties;
import org.example.constant.MessageConstant;
import org.example.exception.TokenException;
import org.example.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 登录过滤器
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;

    private final StringRedisTemplate stringRedisTemplate;


    // 路径匹配器(判断路径是否匹配)
    private final AntPathMatcher  antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入网关过滤器，校验路径");
        // 1、获取请求信息
        ServerHttpRequest request = exchange.getRequest();

        // 2、判断路径是否需要进行登录校验(是否放行)
        if(isExclude(request.getPath().toString())){
            log.info("此路径不需要校验");
            return chain.filter(exchange);
        }

        // 3、获取请求头中的token
        String token = request.getHeaders().getFirst(jwtProperties.getUserTokenName());

        // 获取redis中的token
        String redisToken = stringRedisTemplate.opsForValue().get("TOKEN");

        // 4、判断token是否为空，如果为空，则提示用户未登录
        if(token == null){
            log.info("token为空:{}",token);
            throw new TokenException(MessageConstant.LOGIN_ERROR);
        }

        if (redisToken == null || !redisToken.equals(token)){
            log.info("token不匹配，或过期");
            // 设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

            throw new TokenException(MessageConstant.LOGIN_ERROR);
            // 响应结束
//            return exchange.getResponse().setComplete();
        }


        Claims claims = null;
        // 5、如果token不为空，则进行登录校验
        try {
            log.info("token携带为：{}",token);
            claims = JwtUtils.parseJWT(jwtProperties.getUserSecretKey(), token);
        }catch (Exception e){
            log.info("token解析失败");
            // 设置状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应结束
            return exchange.getResponse().setComplete();
        }
        // token 校验通过，获取用户信息
        log.info("claims：{}", claims);
        String userId = claims.get("userId").toString();
        log.info("token校验通过,用户ID：{}", userId);

        // 6、将用户ID设置到请求头中,返回一个新的请求对象,返回一个Mono对象
        ServerWebExchange build = exchange.mutate()   // 修改请求,对请求头进行修改
                .request(r -> r.header(MessageConstant.HEADER_NAME, userId))
                .build();


        // 放行
        return chain.filter(build);
    }


    /**
     * 判断是否放行
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        // 拿到放行的路径
        List<String> excludePaths = jwtProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        // 优先级, 越小越优先
        return 0;
    }
}
